package commons.base.http;

import java.io.File;

import commons.base.http.jdk.Form;
import commons.base.http.jdk.JdkHttpClient;
import commons.base.http.jdk.JdkHttpGet;
import commons.base.http.jdk.JdkHttpPost;
import commons.base.http.jdk.JdkHttpRequest;
import commons.base.http.jdk.JdkHttpResponse;

/**
 * @author yuan<cihang.yuan@happyelements.com>
 *
 */
public class HttpBuilder {

	private JdkHttpRequest request;
	private Form form = new Form();

	public JdkHttpRequest getRequest() {
		return request;
	}

	public HttpBuilder setRequest(JdkHttpRequest request) {
		this.request = request;
		return this;
	}
	
	public HttpBuilder setProxy(String proxyHost, int proxyPort, String username, String password){
		this.request.setProxy(proxyHost, proxyPort, username, password);
		return this;
	}
	
	/**
	 * 添加http请求头
	 * @param name
	 * @param value
	 * @return
	 */
	public HttpBuilder addHeader(String name, String value){
		request.addHeader(name, value);
		return this;
	}
	
	public HttpBuilder addFormField(String name, String value){
		form.addFormField(name, value);
		return this;
	}
	
	public HttpBuilder setForm(Form form) {
		if(request instanceof JdkHttpGet){
			((JdkHttpGet)request).setForm(form);
		}else if(request instanceof JdkHttpPost){
			((JdkHttpPost)request).setFormBody(form);
		}
		return this;
	}
	
	public HttpBuilder setJsonBody(String json){
		if(request instanceof JdkHttpPost){
			((JdkHttpPost)request).setJsonBody(json);
		}
		return this;
	}
	
	public HttpBuilder apply(){
		if(!form.isEmpty()){
			setForm(form);
		}
		return this;
	}

	public JdkHttpResponse execute(){
		apply();
		
		return JdkHttpClient.defaultClient().execute(request);
	}
	
	public void download(File file){
		apply();
		
		JdkHttpClient.defaultClient().download(request, file);
	}
	
	public static HttpBuilder newPost(String uri){
		return new HttpBuilder().setRequest(new JdkHttpPost(uri));
	}
	
	public static HttpBuilder newGet(String uri){
		return new HttpBuilder().setRequest(new JdkHttpGet(uri));
	}
}
